package com.naiterui.ehp.bs.emr.controller.doctor;

import java.util.List;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.naiterui.ehp.bp.bo.emr.AddPatientRecordInitializeBO;
import com.naiterui.ehp.bp.bo.emr.params.DrCaseParams;
import com.naiterui.ehp.bp.bo.esign.RecomSignParamBO;
import com.naiterui.ehp.bp.constants.SwaggerTag;
import com.naiterui.ehp.bp.constants.SwaggerTags;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bp.support.security.HeaderConstant;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bs.emr.exception.ExceptionCodes;
import com.naiterui.ehp.bs.emr.feign.ESignFeignClient;
import com.naiterui.ehp.bs.emr.feign.IPatientFeignClient;
import com.naiterui.ehp.bs.emr.service.IDrCaseService;
import com.naiterui.ehp.bs.emr.vo.CaseInitVO;
import com.naiterui.ehp.bs.emr.vo.RecordRecomExplainVO;
import com.naiterui.ehp.bs.emr.vo.SaveCaseVO;
import com.naiterui.ehp.bs.emr.vo.SendCaseVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Validated
@RestController
@RequestMapping("emr/case")
@Api(tags = SwaggerTag.DOCTOR + SwaggerTag.MEDICAL_RECORD)
public class EmrDrCaseController {

    public static final Logger LOGGER = LoggerFactory.getLogger(EmrDrCaseController.class);

    @Autowired
    private IDrCaseService drCaseService;

    @Autowired
    private ESignFeignClient esignFeignClient;
    @Autowired
    private IPatientFeignClient patientFeignClient;

    /**
     * 填写病历页初始化信息 患者信息修改为就诊人信息 DrCaseController.initCase()
     *
     * @param doctorId
     * @param patientId
     * @return
     * @Author lichaopi
     * @Date 2018年5月28日
     * @since 1.0.0
     */
    @ApiOperation(value = "填写病历页初始化信息", notes = "填写病历页初始化信息", tags = {SwaggerTags.APP_DOCTOR_INQUIRER})
    @ApiImplicitParams({@ApiImplicitParam(name = "token", value = "令牌", required = true, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = "doctorId", value = "医生id", required = true, dataType = "Long", paramType = "query"),
        @ApiImplicitParam(name = "patientId", value = "患者id", required = true, dataType = "Long", paramType = "query"),
        @ApiImplicitParam(name = "inquirerId", value = "就诊人id", required = true, dataType = "Long", paramType = "query")})
    @PostMapping("initCase")
    public ResponseVO<CaseInitVO> initCase(@NotNull(message = "医生ID不能为null") Long doctorId,
        @NotNull(message = "患者ID不能为null") Long patientId,
        @NotNull(message = "就诊人ID不能为null") Long inquirerId) throws BusinessException {
        LOGGER.info("填写病历传参数,doctorId:{},patientId:{}", doctorId, patientId);
        CaseInitVO vo = drCaseService.initCase(doctorId, patientId, inquirerId);
        return PublicService.returnResponseVO(vo);
    }

    /**
     * 填写病历页多图上传 DrCaseController.uploadCaseImg()
     *
     * @param file
     * @return
     * @Author lichaopi
     * @Date 2018年5月28日
     * @since 1.0.0
     */
    @ApiOperation(value = "填写病历页多图上传", notes = "填写病历页多图上传")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "多图", required = true, dataType = "file", paramType = "add"),
        @ApiImplicitParam(name = "token", value = "令牌", required = true, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = "doctorId", value = "医生id", required = true, dataType = "long", paramType = "add")})
    @PostMapping("uploadCaseImg")
    public ResponseVO<List<String>> uploadCaseImg(@NotNull(message = "医生ID不能为null") Long doctorId,
        @NotNull(message = "上传文件不能为null") MultipartFile... file) throws BusinessException {
        LOGGER.info("填写病历图片上传,doctorId:{}", doctorId);
        if (file.length == 0) {
            LOGGER.error("图片上传文件为空");
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        } else if (file.length > 6) {
            LOGGER.error("图片上传大于6张");
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        List<String> list = drCaseService.uploadFiles(doctorId, file);
        return PublicService.returnResponseVO(list);
    }

    /**
     * 保存病历 DrCaseController.saveDrCase()
     *
     * @param params
     * @return
     * @Author lichaopi
     * @Date 2018年5月28日
     * @since 1.0.0
     */
    @ApiOperation(tags = {SwaggerTags.WX_VIDEO_CONSULT}, value = "保存病历", notes = "保存病历")
    @ApiImplicitParams({@ApiImplicitParam(name = "token", value = "令牌", required = true, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = "doctorId", value = "医生id", required = true, dataType = "long", paramType = "add"),
        @ApiImplicitParam(name = "send", value = "是否发送病历(true是)", dataType = "boolean", paramType = "add")
    })
    @PostMapping("saveDrCase")
    public ResponseVO<SaveCaseVO> saveDrCase(@RequestHeader(value = HeaderConstant.HEADER_ORIGIN) Integer origin,
        @Valid DrCaseParams params, Boolean send) throws BusinessException {
        LOGGER.info("保存病历 请求参数：params = {}, send = {}", params, send);
        Integer requestFrom = this.getRequestFrom(origin);
        SaveCaseVO vo = drCaseService.saveDrMedicalRecord(params, send, requestFrom);
        return PublicService.returnResponseVO(vo);
    }

    /**
     * 医师签名
     *
     * @return
     * @throws BusinessException
     */
    @ApiOperation(value = "医师签名", notes = "医师签名")
    @ApiImplicitParams({@ApiImplicitParam(name = "token", value = "令牌", required = true, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = "recordId", value = "病例id", required = true, dataType = "string", paramType = "add"),
        @ApiImplicitParam(name = "doctorId", value = "医生id", required = true, dataType = "long", paramType = "add"),
        @ApiImplicitParam(name = "uniqueId", value = "视频认证唯一标识", dataType = "string", paramType = "add"),
        @ApiImplicitParam(name = "pin", value = "签名PIN码(根据厂商要求传输, SCCA必填)", required = true, dataType = "string", paramType = "query"),

    })
    @PostMapping("sign")
    public ResponseVO<Void> saveDrCase(@RequestHeader(value = HeaderConstant.HEADER_ORIGIN) Integer origin,
        @NotNull String recordId, @NotNull Long doctorId, String uniqueId, String pin)
        throws BusinessException {
        LOGGER.info("病例签名 请求参数：recordId = {}, doctorId = {}, uniqueId={}", recordId, doctorId, uniqueId);
        Integer requestFrom = this.getRequestFrom(origin);
        drCaseService.sign(recordId, doctorId, uniqueId, pin, requestFrom);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }


    /**
     * 确认发送病例 DrCaseController.confirm()
     *
     * @return
     * @Author lichaopi
     * @Date 2018年5月28日
     * @since 1.0.0
     */
    @ApiOperation(value = "确认发送病例", notes = "确认发送病例")
    @ApiImplicitParams({@ApiImplicitParam(name = "token", value = "令牌", required = true, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = "recordId", value = "病例Id", required = true, dataType = "string", paramType = "add"),
        @ApiImplicitParam(name = "doctorId", value = "医生id", required = true, dataType = "long", paramType = "add"),
        @ApiImplicitParam(name = "force", value = "是否强制推送", dataType = "boolean", paramType = "add"),
        @ApiImplicitParam(name = "consultType", value = "推送来源，1:图文咨询，2：视频咨询", required = true, dataType = "long", paramType = "query"),
        @ApiImplicitParam(name = "consultId", value = "咨询Id", required = false, dataType = "long", paramType = "query"),
        @ApiImplicitParam(name = "send", value = "是否发送病历(true是)", dataType = "boolean", paramType = "add")
    })
    @PostMapping("confirm")
    public ResponseVO<SendCaseVO> confirm(String recordId, Long doctorId, Boolean force, Integer consultType, Long consultId, Boolean send)
        throws BusinessException {
        LOGGER.info("确认发送病例 请求参数：recordId = {}, doctorId = {}, consultType={}, consultId={},force={}", recordId, consultType, consultId, doctorId,
            force);
        SendCaseVO vo = drCaseService.confirm(recordId, doctorId, force, consultType, consultId, send);
        return PublicService.returnResponseVO(vo);
    }

    /**
     * 病历处方说明页信息 DrCaseController.explain()
     *
     * @return
     * @throws BusinessException
     * @Author lichaopi
     * @Date 2018年6月25日
     * @since 1.0.0
     */
    @ApiOperation(value = "病历处方说明", notes = "病历处方说明")
    @ApiImplicitParams({@ApiImplicitParam(name = "token", value = "令牌", required = true, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = "doctorId", value = "医生id", required = true, dataType = "long", paramType = "add")})
    @PostMapping("explain")
    public ResponseVO<RecordRecomExplainVO> explain() {
        RecordRecomExplainVO recordRecomExplainVO = new RecordRecomExplainVO();
        recordRecomExplainVO.setText(ConfigUtil.getString("record.recom.text"));
        recordRecomExplainVO.setImgUrl(ConfigUtil.getString("record.recom.imgUrl"));
        return PublicService.returnResponseVO(recordRecomExplainVO);
    }

    /**
     * 医生添加病历初始化信息
     *
     * @param sessionId
     * @return
     */
    @ApiOperation(value = "医生添加病历初始化信息", notes = "医生添加病历初始化信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "sessionId", value = "会话ID", required = true, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = "inquirerId", value = "就诊人ID", required = true, dataType = "long", paramType = "query")})
    @GetMapping("record/add/initialize")
    public ResponseVO<AddPatientRecordInitializeBO> getAddRecordInitializerInfo(Long inquirerId,String sessionId) {
        // 既往史、过敏史：就诊人信息
        // 线下诊断-主诉：会话对应的病情信息
        return PublicService.returnResponseVO(patientFeignClient.getAddRecordInitializerInfo(inquirerId, sessionId));
    }

    private Integer getRequestFrom(Integer origin) {
        Integer requestFrom = RecomSignParamBO.REQUEST_FROM_APP;
        if (HeaderConstant.HEADER_ORIGIN_DOCTOR_PC == origin) {
            requestFrom = RecomSignParamBO.REQUEST_FROM_PC;
        }
        return requestFrom;
    }
}
